package com.scujj.controller.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scujj.controller.OrderController;
import com.scujj.enums.OfferStatus;
import com.scujj.pojo.Offer;
import com.scujj.pojo.OrderOffer;
import com.scujj.pojo.Result;
import com.scujj.pojo.User;
import com.scujj.service.OfferOrderService;
import com.scujj.service.OfferService;
import com.scujj.service.UserService;
import com.scujj.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/order")
public class OrderControllerImpl implements OrderController {

    @Autowired
    UserService userService;

    @Autowired
    OfferOrderService orderService;

    @Autowired
    OfferService offerService;

    @Override
    @GetMapping("/payFromApi")
    @Transactional
    public Result payOrderFromApi(@RequestParam(value = "oid",defaultValue = "0") String oid) {
        OrderOffer order = orderService.getById(oid);
        if(order==null){
            return Result.error("不存在此订单");
        }
        Offer offer=offerService.getById(order.getOid());
        if(offer==null){
            return Result.error("订单错误:未找到求助");
        }
        if(order.getStatus()!= OfferStatus.UNPAID.state){
            return Result.error("订单状态不支持");
        }
        if(offer.getStatus()!=OfferStatus.UNPAID.state){
            return Result.error("求助状态不支持");
        }
        offer.setStatus(OfferStatus.PAID.state);
        order.setStatus(OfferStatus.PAID.state);
        if(!offerService.updateById(offer)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("求助保存错误");
        }
        if(!orderService.updateById(order)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("订单保存错误");
        }
        return Result.success("支付成功");
    }

    @Override
    @GetMapping("/payFromWallet")
    @Transactional
    public Result payOrderFromWallet(@RequestHeader  HashMap<String, String> header,@RequestParam String oid) {
        OrderOffer order = orderService.getById(oid);
        if(order==null){
            return Result.error("不存在此订单");
        }
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        Offer offer=offerService.getById(order.getOid());
        if(offer==null){
            return Result.error("订单错误:未找到求助");
        }
        if(offer.getPrice()>user.getMoney()){
            return Result.error("钱包金额不足");
        }
        HashMap<String, Long> useMoneyParams=new HashMap<>();
        useMoneyParams.put("id",user.getId());
        useMoneyParams.put("money",offer.getPrice());
        Result r= payOrderFromApi(oid);
        if(r.getCode()==0){
            userService.useMoney(useMoneyParams);
            return r;
        }
        return r;
    }

    @Override
    @GetMapping("/create")
    @Transactional
    public Result createOrder(@RequestHeader HashMap<String, String> header,@RequestParam String pid) {
        Offer offer=offerService.getById(pid);
        if(offer==null){
            return Result.error("未找到求助");
        }
        if(offer.getStatus()!=OfferStatus.UNPAID.state){
            return Result.error("求助状态不支持");
        }
        QueryWrapper<OrderOffer> orderWrapper = new QueryWrapper<>();
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);


        offer.setUser(user);
        orderWrapper.eq("oid",null);
        OrderOffer t_order = orderService.getOne(orderWrapper);
        if(t_order!=null){
            return Result.error("已有订单被创建");
        }
        OrderOffer order = new OrderOffer();
//        order.setUid(user.getId());
        order.setOid(offer.getId());
        order.setStatus(OfferStatus.UNPAID.state);
        order.setStartTime(new Date());
        orderService.save(order);

        order.setOffer(offer);
        order.setUser(user);
        return Result.success("创建订单成功",order);
    }


    // 此处使用了offer id, 而不是order id, 因为前端只拿到了offer的信息
    @Override
    @GetMapping("/confirm/{oid}")
    @Transactional
    public Result confirmOrder(@RequestHeader HashMap<String, String> header,@PathVariable String oid) {
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);

        Offer offer=offerService.getById(oid);
        if(offer==null){
            return Result.error("订单错误:未找到求助");
        }

        QueryWrapper<OrderOffer> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("oid",offer.getId());
        OrderOffer order = orderService.getOne(orderWrapper);
        if(order==null){
            return Result.error("不存在此订单");
        }

        if(!Objects.equals(offer.getUid(), user.getId())){
            return Result.error("你没有确认此订单的权限");
        }
        order.setStatus(OfferStatus.END.state);
        offer.setStatus(OfferStatus.END.state);

        HashMap<String,Long> addMoneyParams=new HashMap<>();
        addMoneyParams.put("id",order.getUid());
        addMoneyParams.put("money",offer.getPrice()*3); // 加上之前扣的钱
        userService.addMoney(addMoneyParams);
        orderService.updateById(order);
        offerService.updateById(offer);
        return Result.success("确认成功");
    }

    @Override
    @GetMapping("/list")
    public Result orderList(@RequestHeader HashMap<String, String> header,
                            @RequestParam(value = "page",defaultValue = "1") int page,
                            @RequestParam(value = "limit",defaultValue = "5") int limit) {

        if(page<1){
            return Result.error("页数不能小于1");
        }
        if(limit<1){
            return Result.error("每页数量不能小于1");
        }
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        QueryWrapper<OrderOffer> wrapper = new QueryWrapper<>();
        wrapper.eq("uid",user.getId());
        Page<OrderOffer> pageObj = new Page<>(page,limit);
        wrapper.orderByDesc("startTime");
        orderService.page(pageObj,wrapper);
        List<OrderOffer> list = pageObj.getRecords();
        list.forEach(order -> order.setOffer(offerService.getById(order.getOid())));
        return Result.success(list);
    }


    @Override
    @GetMapping("/accepted")
    public Result acceptedOffer(@RequestHeader HashMap<String, String> header,
                                @RequestParam(value = "page",defaultValue = "1") int page,
                                @RequestParam(value = "limit",defaultValue = "5") int limit) {
        Result result=userService.getUserByToken(header);
        if(result.getCode()==-1){
            return result;
        }
        User user = ResultUtil.singleTrans(result.getData(),User.class);
        QueryWrapper<OrderOffer> wrapper = new QueryWrapper<>();
        wrapper.eq("uid",user.getId());
        wrapper.orderByDesc("startTime");
        Page<OrderOffer> pageObj = new Page<>(page,limit);
        orderService.page(pageObj,wrapper);
        List<OrderOffer> list = pageObj.getRecords();
        list.forEach(order -> order.setOffer(offerService.getById(order.getOid())));
        return Result.success(list);
    }
}
